package ooo.reindeer.cedf.components.flow;

import ooo.reindeer.cedf.Event;
import ooo.reindeer.cedf.components.handler.IEventHandler;
import ooo.reindeer.commons.Property;
import ooo.reindeer.logging.ILogger;
import ooo.reindeer.logging.LogUtil;


public class FlowEventHandler implements IEventHandler<FlowResult> {

    private static final ILogger logger = LogUtil.getLogger(FlowEventHandler.class);

    private final Flow flow = new Flow();
    String id;
    @Override
    public boolean init(String id, Property config) {
        logger.info("init:id=[{}]	config=[{}]", id, config);
        this.id=id;
        if (id.isEmpty()) {
            return false;
        }
        String flowId=config.getValue("flow","");

        if(flowId.isEmpty()) return false;
        Property flow_property = Property.getPropertyObject("cedf.flow." + flowId);
        if(!flow.init(flowId, flow_property)){
            logger.error("init flow error: id=[{}] config=[{}]",flowId,flow_property);
            throw new RuntimeException(flowId + " init error");
        }
        return true;
    }

    @Override
    public FlowResult onEvent(Event event) {
        if(logger.isDebugEnabled()) {
            logger.debug("onEvent:event=[{}]", event);
        }
        FlowResult result = (FlowResult) flow.handle(event);
        if(logger.isDebugEnabled()) {
            logger.debug("onResult:result=[{}]  event=[{}]", result, event);
        }
        return result;
    }

}
